package pers.jing.android.helper.widget

import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowDropDown
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.sp

@Composable
fun Spinner(name: String,
            placeHolder: String,
            data: List<String>, selectedIndex: Int,
            modifier: Modifier,
            onSelect:(Int, String) -> Unit) {
    val text = if (selectedIndex >= 0 && selectedIndex < data.size) {
        data[selectedIndex]
    } else {
        ""
    }
    var showSelectDialog by remember {
        mutableStateOf(false)
    }
    OutlinedTextField(
        value = text,
        textStyle = TextStyle(fontSize = 17.sp),
        onValueChange = {

        },
        trailingIcon = {
            IconButton(onClick = {
                if (data.isNotEmpty()) {
                    showSelectDialog = true
                }
            }) {
                Icon(imageVector = Icons.Rounded.ArrowDropDown,
                    contentDescription = name)
            }
        },
        placeholder = {
            Text(
                text = placeHolder
            )
        },
        readOnly = true,
        singleLine = true,
        modifier = modifier
    )
    if (showSelectDialog) {
        SelectDialog(name, data, selectedIndex, onSelect = { index, text ->
            showSelectDialog = false
            onSelect(index, text)
        }, onDismiss = {
            showSelectDialog = false
        })
    }
}